package com.woniuxy.portal.controller;

import cn.hutool.core.util.RandomUtil;
import com.rabbitmq.client.AMQP;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/email")
public class EmailController {
    @Value("${spring.mail.username}")
    private String from;
    // 注入RabbitTemplate，用于发送消息到消息队列
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostMapping("/send/{email}")
    public String sendEmail(@PathVariable("email") String email) {
        // 验证码
        String code = RandomUtil.randomNumbers(4);
        // 封装邮件内容
        Map<String, String> emailMap = new HashMap<>();
        emailMap.put("from", from);
        emailMap.put("to", email);
        emailMap.put("subject", "验证码邮件");
        emailMap.put("text", code);

        AMQP.Queue.DeclareOk declareOk = rabbitTemplate.execute(action -> {
            return action.queueDeclarePassive("q-email");
        });

        // 队列消息最大长度： 10
        int max_count = 10;
        // 获取当前队列中有多少消息未处理
        int count = declareOk.getMessageCount();
        if (count >= max_count * 0.8) {
            // 说明队列中已经有大量消息积压，消息投递到死信中
        } else {
            // 发送消息
            rabbitTemplate.convertAndSend("q-email", emailMap);
        }
        return "ok";
    }
}
